package com.android.manghe.search.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import android.view.View
import android.view.inputmethod.EditorInfo
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DisplayUtil
import com.android.base.tools.SerializeUtil
import com.android.base.tools.ToastUtil
import com.android.base.tools.permission.OnPermissionResultListener
import com.android.base.tools.permission.PermissionUtil
import com.android.manghe.R
import com.android.manghe.box.model.MessageEvent
import com.android.manghe.common.model.ShowBoxEvent
import com.android.manghe.common.model.ShowIndexEvent
import com.android.manghe.config.Config
import com.android.manghe.market.adapter.MarketGoodsGridAdapter
import com.android.manghe.market.model.MarketAuctionRes
import com.android.manghe.search.adapter.SearchHistoryGridAdapter
import com.android.manghe.search.presenter.PBigMarketSearch
import com.android.manghe.utils.ListUtil
import com.android.manghe.view.GridAuctionSpacesItemDecoration
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.activity_splash.*
import me.nereo.multi_image_selector.MultiImageSelector
import org.greenrobot.eventbus.EventBus

class SearchBigMarketActivity : MVPActivity<PBigMarketSearch>(), IRefresh,
    OnPermissionResultListener {


    override fun getRefreshView(): SmartRefreshLayout {
        return findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        p.search(true, "")
    }

    override fun onLoad() {
        p.search(false, "")
    }

    private var mAdapter: MarketGoodsGridAdapter? = null
    private var mHistoryAdapter: SearchHistoryGridAdapter? = null

    private var mSearchHistoryList = arrayListOf<String>()

    companion object {
        fun showActivity(context: Context) {
            val intent = Intent(context, SearchBigMarketActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun showToolBarType(): ETitleType {
        return ETitleType.NO_TITLE
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_search
    }

    override fun initData(savedInstanceState: Bundle?) {
        PermissionUtil.requestPermissions(
            this, this,
            Permission.WRITE_EXTERNAL_STORAGE
        )
        Bus.observe<ShowBoxEvent>().subscribe {
          finish()
        }.registerInBus(this)
        initListener()
    }


    override fun onGranted(permissions: MutableList<String>?) {
        val localHistoryListTemp = SerializeUtil.loadFile(Config.SerializeSearchHistory)
        localHistoryListTemp?.let {
            mSearchHistoryList.addAll(it as List<String>)
        }
        layoutHistory.visibility =
            if (mSearchHistoryList.isNullOrEmpty()) View.GONE else View.VISIBLE
        if (!mSearchHistoryList.isNullOrEmpty()) {
            recyclerView.layoutManager =
                GridLayoutManager(this, 3)
            mHistoryAdapter = SearchHistoryGridAdapter(mSearchHistoryList)
            recyclerView.adapter = mHistoryAdapter
        }
        recyclerViewData.layoutManager =
            GridLayoutManager(this, 2)
        recyclerViewData.addItemDecoration(
            GridAuctionSpacesItemDecoration(
                DisplayUtil.dip2px(
                    this,
                    8f
                )
            )
        )
        mAdapter = MarketGoodsGridAdapter(
            this, false,
            ArrayList<MarketAuctionRes.AuctionInfo>()
        )
        recyclerViewData.adapter = mAdapter

        mHistoryAdapter?.setListener(object : SearchHistoryGridAdapter.ISearchHistoryListener {
            override fun onClick(content: String?) {
                if (content != null) {
                    search(content)
                    etSearch.setText(content)
                    etSearch.setSelection(content.length)

                }
            }
        })
    }

    private fun setPriceSortState(type: Int) {
        p.mPriceSort = type
        when (type) {
            0 -> ivSort.setImageResource(R.mipmap.ic_sort)
            1 -> ivSort.setImageResource(R.mipmap.ic_sort_top)
            2 -> ivSort.setImageResource(R.mipmap.ic_sort_down)
        }
    }

    private fun setFilter(type: Int) {
        if (type != 3) {
            setPriceSortState(0)
        } else {
            when (p.mPriceSort) {
                0 -> setPriceSortState(1)
                1 -> setPriceSortState(2)
                2 -> setPriceSortState(1)
            }
        }
        tvComprehensive.setTextColor(
            ContextCompat.getColor(
                this,
                if (type == 0) R.color.red else R.color.black
            )
        )
        tvSalesVolume.setTextColor(
            ContextCompat.getColor(
                this,
                if (type == 1) R.color.red else R.color.black
            )
        )
        tvDiscount.setTextColor(
            ContextCompat.getColor(
                this,
                if (type == 2) R.color.red else R.color.black
            )
        )
        tvPrice.setTextColor(
            ContextCompat.getColor(
                this,
                if (type == 3) R.color.red else R.color.black
            )
        )
        if (type != 3 && p.mFilterType == type) {
            return
        }
        p.mFilterType = type
        p.search(true, etSearch.text.toString().trim())
    }

    fun initListener() {
        tvCancel.setOnClickListener { finish() }
        tvComprehensive.setOnClickListener {
            //综合
            setFilter(0)
        }
        tvSalesVolume.setOnClickListener {
            //销量
            setFilter(1)
        }
        tvDiscount.setOnClickListener {
            //折扣
            setFilter(2)
        }
        layoutPrice.setOnClickListener {
            //价钱
            setFilter(3)
        }
        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val text = etSearch.text.toString().trim()
                if (text.isEmpty()) {
                    ToastUtil.showShort(this@SearchBigMarketActivity, "请输入搜索内容")
                    true
                } else {
                    mSearchHistoryList.add(text)
                    ListUtil.removeDuplicate(mSearchHistoryList)
                    SerializeUtil.saveFile(mSearchHistoryList, Config.SerializeSearchHistory)
                    mHistoryAdapter?.update(mSearchHistoryList)
                    search(text)
                    true
                }
            }
            false
        }
    }



    private fun search(text: String) {
        showLoadingDialog()
        layoutHistory.visibility = View.GONE
        refreshLayout.visibility = View.VISIBLE
        p.search(true, text)
    }

    fun searchFail(text: String?) {
        hideLoadingDialog()
        layoutHistory.visibility = View.VISIBLE
        refreshLayout.visibility = View.GONE
        ToastUtil.showShort(this, if (text.isNullOrEmpty()) "搜索失败" else text)
        layoutFilter.visibility = if (mAdapter!!.data.isNotEmpty()) View.VISIBLE else View.GONE
    }

    fun update(dataList: List<MarketAuctionRes.AuctionInfo>) {
        hideLoadingDialog()
        mAdapter?.let {
            it.update(dataList)
        }
        layoutFilter.visibility = View.VISIBLE
    }


    fun setCanLoadMore(canLoadMore: Boolean) {
        refreshLayout.isEnableLoadMore = canLoadMore
    }

    fun noData() {
        hideLoadingDialog()
        layoutHistory.visibility = View.VISIBLE
        refreshLayout.visibility = View.GONE
        layoutFilter.visibility = View.GONE
        ToastUtil.showShort(this, "无搜索结果")
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }
}